﻿using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using TY.UC.Common;
using TY.UC.Common.Extension;

namespace TY.UT.Oss.AliYun
{
    /// <summary>
    /// 阿里云图片操作
    /// </summary>
    public class AliImageHelper
    {
        private static readonly string Bucket = "Bucket".GetStrValue();
        private static readonly string AccessKey = "AccessKey".GetStrValue();
        private static readonly string SecretKey = "SecretKey".GetStrValue();
        private static readonly string Endpoint = "EndPoint".GetStrValue();
        private static readonly string ImgRunEnv = "ImgRunEnv".GetStrValue(); //Product正式环境

        /// <summary>
        /// 上传图片至阿里云
        /// </summary>
        /// <param name="bytes">上传图片</param>
        /// <param name="path">文件存储路径，包含文件名</param>
        /// <returns>空为失败，成功则返回存储路径</returns>
        public static string UpByteToAliYun(byte[] bytes,  string path)
        {
            if (bytes == null) return "";
            try
            {
                string filekey = ImgRunEnv.ToLower() == "Product".ToLower()
                    ? string.Format("product/{0}", path)
                    : string.Format("test/{0}", path);
                new OssClient(Endpoint, AccessKey, SecretKey).PutObject(Bucket, filekey, new MemoryStream(bytes));
                return "http://" + Bucket + "." + Endpoint + "/"+ filekey;
            }
            catch (OssException ex)
            {
                LogHelper.WriteLog("AliImageHelper", "AliImageHelper-UpByteToAliYun()出现Oss异常，path=" + path, ex);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("AliImageHelper", "AliImageHelper-UpByteToAliYun()出现普通异常，path=" + path, ex);
            }
            return "";
        }
    }
}
